<?php

namespace brand\traits;

use app\admin\controller\Base;
use app\admin\model\ConfigValue;
use brand\Brand;
use brand\build\Columns;
use brand\components\Component;
use brand\logic\BrandHelper;
use brand\page\Form;
use brand\page\Page;
use brand\page\Table;
use brand\tools\Functions;
use think\App;
use think\facade\Db;


/**
 * 配置分类
 */

trait Config
{
    public $config_table = 'config';
    public $config_value_table = 'config_value';

    public function __construct(App $app)
    {

        $this->curdName = 'config';

        $brand_addon = request()->param('brand_addon');
        if ($brand_addon){
            $addon_config = get_addon_info($brand_addon);
            $table_prefix = $addon_config['table_prefix'] ?? '';
            $this->config_table = $table_prefix.$this->config_table;
            $this->config_value_table = $table_prefix.$this->config_value_table;
        }
        \brand\logic\Config::$addon_name = "";
        \brand\logic\Config::$curd_path = 'extend/brand/tables/';

        parent::__construct($app);
    }

    public function table_init()
    {
        $config = Table::getConfig();

        foreach ($config['custom_header_buttons'] as $key => $custom_header_button) {
            $config['custom_header_buttons'][$key]['url'] = '/' .request()->param('brand_addon') . '/' . request()->param('brand_module') . $custom_header_button['url'];
        }
        foreach ($config['custom_right_buttons'] as $key => $custom_right_button) {
            $config['custom_right_buttons'][$key]['url'] = '/' .request()->param('brand_addon') . '/' . request()->param('brand_module') . $custom_right_button['url'];
        }

        Table::setConfig($config);
        Table::$custom_button_header = [];
        Table::$custom_button = [];
        Table::setPageConfig();

    }

    public function db_reset($db)
    {
        if ($this->curdName == 'config'){
            return Db::name($this->config_table);
        }else{
            return Db::name($this->config_value_table);
        }
    }

    /**
     * 配置Value
     */
    public function values()
    {

        if (request()->isAjax()){
            $params = request()->post();
            foreach ($params as $label => $param) {
                if (is_array($param)) $param = json_encode($param);

                $_config = Db::name($this->config_value_table)->where(['label'=>$label])->find();
                if (!$_config) continue;
                if ($_config['column_method'] == 'Date'){
                    $param = BrandHelper::ms2time($param);
                }

                Db::name($this->config_value_table)->where(['label'=>$label])->update(['value'=>$param]);
            }

            return _success('操作成功');
        }
        $list = Db::name($this->config_table)->order('weigh asc')->select();

        $tabs_options = [];
        $values = [];
        foreach ($list as $item) {
            $_config_name = $item['config_name'] ?? "";
            $tabs_options[$_config_name] = [];
            $configValue = Db::name($this->config_value_table)->where('config_id',$item['config_id'])->order('weigh asc')->select();
            foreach ($configValue as $value) {
                $form = [];
                $ClassName = \brand\logic\Config::BRAND_NAMESPACE . ( Functions::toCamelCase($value['column_method']) );
                $form['method'] = $value['column_method'];
                $table =[];
                $columns_param = json_decode($value['column'],1) ?? [];

                if (class_exists($ClassName) && $columns_param){
                    $ClassObject = new $ClassName();
                    $params['param'] = $columns_param;
                    [$form,$table] = $ClassObject->methodFormConf($form,$table,$params);

                }
                $form['marker'] = $value['remark'];
                if (app()->isDebug()){
                    $form['marker'] .= '  '. $item['config_code'].'.'.$value['label'];
                }
                $column['form'] = $form;
                $column['title'] = $value['value_title'];
                if (is_numeric($value['value'])) $value['value'] = (float)$value['value'];
                $values[$value['label']] = $value['value'];
                $tabs_options[$_config_name][$value['label']] = $column;
            }
            

        }

        $tabs_columns['setting'] = Brand::Builder('','tabs')->form(['tabs_options'=>$tabs_options,'tabs_values'=>$values])->build();
        $columns = Form::buildForm($tabs_columns,[]);


        $mixin_column[] = Form::$SurfaceForm->column('page','')->el('page')->props(['text'=>'管理配置组','url'=>url('config/index')->build()]);

        Form::$SurfaceForm->columns(array_merge($mixin_column,$columns));
        return Form::$SurfaceForm->view();
    }

    /**
     * 分类删除之前
     * @param $curdName
     * @param $pk
     * @param $id
     */
    public function delete_before($curdName, $pk, $id)
    {
        if (Db::name($this->config_value_table)->where(['config_id'=>$id])->find()){
            $this->error('此设置下有字段，请先删除字段');
        }
        return [$pk,$id];
    }


    /**
     * 子配置信息列表
     */
    public function ConfigValue()
    {
        $this->curdName = 'config_value';
        parent::init_curd();

        Table::$table_data_url = url('ConfigValue',request()->get())->build();;
        Table::$add_url = url('ConfigValueAdd',request()->get())->build();;
        Table::$edit_url = url('ConfigValueEdit',request()->get())->build();;
        Table::$delete_url = url('ConfigValueDel',request()->get())->build();;
        return parent::index();
    }

    /**
     * 新增子配置信息
     */
    public function ConfigValueAdd()
    {
        $this->curdName = 'config_value';
        Table::$add_url = url('ConfigValueAdd',request()->get())->build();
        parent::init_curd();
        return parent::add();
    }
    /**
     * 修改子配置信息
     */
    public function ConfigValueEdit()
    {
        $this->curdName = 'config_value';
        Table::$edit_url = url('ConfigValueEdit',request()->get())->build();
        parent::init_curd();
        return parent::edit();
    }
    /**
     * 删除子配置信息
     */
    public function ConfigValueDel()
    {
        $this->curdName = 'config_value';
        return parent::del();
    }



    /**
     * 子配置信息表单构造
     * @param $raw
     */
    public function form_before_build($raw)
    {
        if ($this->curdName != 'config_value') return $raw;
        $columns = Columns::getConfig();

        //类型
        $brandList = \brand\logic\Config::getBrandList();
        $brandOptions = BrandHelper::formatOptions($brandList);

        $columns['column_method'] = [
            'form'  =>  [
                'method'    =>  'select',
                'options' =>$brandOptions,
            ],
            'title' =>  '类型'
        ];

        $raw['column_method'] = $raw['column_method'] ?? 'Input';

        //循环支持的所有表单
        foreach ($brandList as $brandMethod => $brandLabel) {
            $ClassName = \brand\logic\Config::BRAND_NAMESPACE . Functions::toCamelCase($brandMethod);
            if (class_exists($ClassName)){

                $ClassObject = new $ClassName();
                $methodConfig = $ClassObject->buildConfigColumn([],'column_method');

                $columns[$brandMethod] = $methodConfig['column'];
                $raw[$brandMethod] = $raw['column'] ?? $methodConfig['value'];

            }
        }
        Form::setAsyncUrl (url('submitFromConf',request()->get())->build());
        Columns::setConfig($columns);
        return $raw;
    }

    /**
     * 子配置信息保存
     */
    public function submitFromConf()
    {
        $config_id = request()->get('config_id');
        $post = request()->post();

        $data['value_title'] = $post['value_title'] ?? "";
        if($config_id) $data['config_id'] = $config_id;
        $data['label'] = $post['label'] ?? "";
        $data['weigh'] = $post['weigh'] ?? 0;
        $data['remark'] = $post['remark'] ?? '';
        if (isset($post['value']) && $post['value']) $data['value'] = $post['value'];
        $data['column_method'] = $post['column_method'] ?? "";
        $data['column'] = json_encode($post[$data['column_method']] ?? []);


        if (isset($post['id']) && $post['id']){
            Db::name($this->config_value_table)->where('id',$post['id'])->update($data);
        }else{
            Db::name($this->config_value_table)->insert($data);
        }

        return _success('操作成功');
    }


}